/*
 * 区域报警
 * @version 3.0.2
 * @author peng
 * */

function Enclosure ( map , mapType , url){
	this.map = map;
	this.mapType = mapType;
	this.ECAR_SERVICE_URL  = url; 
	this.currentShape = undefined;
	this.latLng = new goome.maps.LatLng(0, 0);
	this.zoom = mapType == 'baidu' ? 17 : 16;
	this.currentRadius = 200;
	this.currentUser = undefined;
	this.currentDragPos = undefined;
	this.ct = document.getElementById("mapcanvas");
	this.isInit = false;
	this.init();
};

Enclosure.prototype = {
	//初始化创建对象	
	init : function () {
		var _this = this;
		_this.drawCycle(_this.latLng, _this.currentRadius);
		_this.creatMarker(_this.latLng, _this.creatRangeCt());
		_this.creatDragMarker();
		_this.creatMouseTips();
		_this.isInit = true;
		setTimeout(function(){_this.cancel();},	0);
	},	
	//设置围栏在地图中心
	setCenter : function () {
		var map = this.map;
		map.setZoom(this.zoom);
		map.setCenter(this.latLng);
	},
	//取得当前弹出marker数据
	getCurrentNode : function () {
		var userList = GFRAME.userList?GFRAME.userList:parent.GFRAME.userList;
		var unode = userList["U" + GFRAME.openPopMarkerUid];
		this.lng = unode[GFRAME.listKey.jingdu];
		this.lat = unode[GFRAME.listKey.weidu];
		this.latLng = new goome.maps.LatLng(this.lat, this.lng);
		this.userName = unode[GFRAME.listKey.user_name];
		this.currentUser = GFRAME.openPopMarkerUid;
	},
	//调用区域报警操作
	setEnclosure : function ( type , value) {
		var _this = this;
		this.cancel();
		var dialog = window.win?win:parent.win;
		dialog.closeWinLayer();
		this.getCurrentNode();
		this["set" + type](value);
	},
	//默认200米
	setDefault : function (callback) {
		this.submit(200, this.currentUser, callback);
	},
	//自定义范围
	setCustom : function () {
		this.setCenter();
		this.currentRadius = 200;
		this.currentDragPos = undefined;
		this.lastLat = undefined;
		this.lastLng = undefined;
		this.currentShape.setCenter(this.latLng);
		this.currentShape.setRadius(this.currentRadius);
		this.marker.update({position: this.latLng, text: this.creatRangeCt(formatKm2M(200/1000))});				
		this.setDragMarkerPos();
		this.dragMarker.setVisible(true);
		this.marker.setZIndex(1000);	
		this.marker.showMarker();
	},
	//查看区域
	setView : function () {
		var _this = this;
		var param = "user_id=" + this.currentUser + "&mds=" + window.mds + "&mapType=" + _this.mapType;
		var url = _this.ECAR_SERVICE_URL + "/FenceInfoService?method=getFenceInfo";

		$.ajax({
			url: url,
			data: param,
			dataType: "jsonp",
			success: function(obj){
				if(obj && obj.success && obj.records[0]){
					var r = obj.records[0];
					r = r.shape_param.split(',');
					var latLng = new goome.maps.LatLng(r[0], r[1]);
					_this.map.setZoom(_this.zoom);
					_this.map.setCenter(latLng);
					_this.currentShape.setCenter(latLng);
					_this.currentShape.setRadius(Number(r[2]));
					_this.marker.update({position:latLng, text: _this.creatViewCt(formatKm2M(r[2]/1000))});
					_this.marker.setZIndex(1000);	
					_this.marker.showMarker();									
				}else if(obj && !obj.success && confirm(lg.noFence)){
					//查看无围栏时自定义范围
					_this.setCustom();					
				} 
			}
		});	
	},
	//启用停用
	setSwitch : function ( value ) {
		var v = value.getAttribute("name"), uid = value.getAttribute("uid");
		var url = _CONFIG_.UPDATE_URL + 'FenceInfoService?method=switchFence';
		var param = "validate_flag=" + v + "&user_id=" + this.currentUser + "&id=" + uid + "&mds=" + window.mds;
		
		$.ajax({
			url: url,
			data: param,
			dataType: "jsonp",
			success: function(obj){
				var msg = (v == 1 ? lg.enable : lg.out);
				if(obj.success){
					alert(msg + lg.msgtit1);
				}else{
					alert(msg + lg.msgtit2);	
				}
			}
		});			
	},
	//设置所有marker隐藏
	resetMarkerPos : function () {
		if(this.currentUser !== GFRAME.openPopMarkerUid && this.isInit 
				&& this.currentShape && this.dragMarker && this.marker){
			this.cancel();
		}
	},
	//自定义操作栏
	creatRangeCt : function ( range ) {
		range = range || formatKm2M(200/1000); 
		var rangeCt = [];
		rangeCt.push("<span>&nbsp;&nbsp;</span><br/><span style='width:120px;color:gray;'><span><span style='color:#5461D9;font-weight:bold'>");
		rangeCt.push(this.userName + "</span>&nbsp;" + lg.mapRange + "&nbsp;<span style='color:#5461D9;font-weight:bold'>" + range + "</span></span>&nbsp;[<a href='javascript:;' onmouseover='customAlarmTips(\"over\",this)' onmouseout='customAlarmTips(\"out\",this)'>?</a>]<br/>");
		rangeCt.push("<span><br/><span>" + lg.enclocureInfo + "：</span><span><a href='javascript:;' style='font-weight:bold;' onclick='ZoneAlarm.save();parent.GFRAME.selectUser(" + this.currentUser + ")'>");
		rangeCt.push(lg.ok + "</a></span>&nbsp;|&nbsp;&nbsp;<span><a href='javascript:;' onclick='ZoneAlarm.cancel();' style='font-weight:bold;'>" + lg.cancel + "</a><br/></span></span>");
		rangeCt.push("<span>&nbsp;&nbsp;</span><br/></span>");
		return rangeCt.join('');
	},
	//查看报警区域
	creatViewCt : function ( range ) {
		range = range || formatKm2M(200/1000); 
		var rangeCt = [];
		rangeCt.push("<span>&nbsp;&nbsp;</span><br/><span style='width:120px;color:gray;'><span><span style='color:#5461D9;font-weight:bold'>");
		rangeCt.push(this.userName + "</span>&nbsp;" + lg.mapRange + "&nbsp;<span style='color:#5461D9;font-weight:bold'>" + range + "</span></span>&nbsp;&nbsp;[<a onclick='ZoneAlarm.cancel();parent.GFRAME.selectUser(" + this.currentUser + ")'; href='javascript:;'>" + lg.clos + "</a>]<br/>");
		rangeCt.push("<span>&nbsp;&nbsp;</span><br/></span>");
		return rangeCt.join('');
	},	
	//设置围栏半径
	setRadius : function ( radius ) {
		this.currentShape.setRadius(radius);
	},
	//创建圆形区域
	drawCycle : function ( point , radius ) {
		var _this = this;
		var mapDragHandler = function(){
			_this.setMouseTipDisplay('none');			
		};
		
	    var circle = new goome.maps.Circle({center: point, strokeColor: "red", strokeOpacity: 0.7,strokeWeight: 2,
	        fillColor: "gray", fillOpacity: 0.5, map: this.map, radius: radius
	    });  	
	    goome.maps.event.addListener(this.map, "dragstart", function(e){
	    	mapDragHandler();
		});
	    goome.maps.event.addListener(this.map, (this.mapType == 'BAIDU' ? "zoomstart" : "zoom_changed"), function(e){
	    	mapDragHandler();
		});	
	    
	    this.currentShape = circle;
	},
	//创建地图marker
	creatMarker : function ( point , txt) {
		var _this = this;
		var iconUrl = _this.ECAR_SERVICE_URL + "/images/comm/red_01.gif";
		this.marker = new PopupMarker({position: point, map: this.map, showpop: false, icon: iconUrl, text: txt, id: 'm_enclosure'});
	},
	//创建拖放marker
	creatDragMarker : function () {
		var _this = this;		
		var pos = this.getDragMarkerPos();
		var icon = _this.ECAR_SERVICE_URL + '/images/comm/icon-point.png';
		
		var dragStart = function(e){
			var dis = _this.getInstance(e);
			_this.currentRadius = dis*1000;
			var txt = formatKm2M(_this.currentRadius/1000);
			_this.marker.update({text: _this.creatRangeCt(txt)});
			_this.setMouseTipText(txt);
			var pos = _this.getMousePos(e);
			_this.creatMouseTips(pos.left, pos.top);
			_this.setMouseTipDisplay('block');			
		};
		
		var dragHandler = function(e){
			var dis = _this.getInstance(e);
			_this.currentRadius = dis*1000;  
			if(_this.currentRadius<200){
				_this.setRadius(_this.currentRadius = 200);
				_this.setDragMarkerPos();
			}else{
				_this.setRadius(_this.currentRadius);
			}
			_this.marker.update({text: _this.creatRangeCt(formatKm2M(_this.currentRadius/1000))});			
			_this.setMouseTipDisplay('none');
		};
		
		var dragMarker = new goome.maps.Marker({
			  icon : icon,
	          draggable: true,
	          enableDragging: true,
	          map : this.map,
	          position : pos
	     },{width:20,height:34},{width:10,height:34});		
		
		goome.maps.event.addListener(dragMarker, (this.mapType == 'BAIDU' ? 'dragging' : 'drag'), function(e) {
			dragStart(e);
	    });	
		goome.maps.event.addListener(dragMarker, "dragend", function(e){
			dragHandler(e);
			_this.currentDragPos = _this.getLatLngOffset(e); 
		});		
		
		this.dragMarker = dragMarker;	
	},
	//计算经纬度差
	getLatLngOffset : function ( e ) {
		var _this = this, point = e.point;
		point = point || {lat: e.latLng.Pa, lng: e.latLng.Qa};					
		return {x: point.lng - Number(_this.lng), y: point.lat - Number(_this.lat)};
	},
	//计算2点之间的距离
	getInstance : function ( e ) {
		var _this = this, point = e.point;
		point = point || {lat: e.latLng.lat(), lng: e.latLng.lng()};			
		var _dis = distance(point.lat, point.lng, _this.lat, _this.lng, 0);
		return _dis;
	},
	//取得经纬度
	getPosition : function () {
		var shape = this.currentShape;
		var bounds = shape.getBounds().getNorthEast();
		var center = shape.getCenter();
		var lat = center.lat();	
		var lng = bounds.lng();
		return new goome.maps.LatLng(lat - 0.0014, lng - 0.00075);
	},
	//取得拖动marker初始位置
	getDragMarkerPos : function () {
		var pos = this.getPosition();
		return pos;
	},
	//设置拖动marker初始位置	
	setDragMarkerPos : function () {
		var pos = this.getPosition();
		this.dragMarker.setPosition(pos); 
	},	
	//取消围栏地图显示
	cancel : function () {
		this.currentShape.setRadius(0);
		this.currentShape.setCenter(new goome.maps.LatLng(0, 0));
		if(this.marker.container_) this.marker.hideMarker();
		this.setMouseTipDisplay('none');
		this.dragMarker.setVisible(false);
	},
	//启用当前围栏
	save : function () {
		this.submit(this.currentRadius, this.currentUser);
	},
	//创建鼠标提示
	creatMouseTips : function ( left , top ) {
		if(!this.mouseTip){
			var doc = document.createElement('div');
			doc.style.cssText = "display:none;position:absolute;background-color:#EFF2C1;padding:3px;border:1px solid gray";
			doc.innerHTML = "<span id='mousetip'></span>";
			document.body.appendChild(this.mouseTip = doc);
		}else{
			var st = this.mouseTip.style;
			st.left = left + 'px';
			st.top = top + 'px';
		}
	},
	//设置调整范围时拖动提示
	setMouseTipText : function ( txt ) {
		 document.getElementById("mousetip").innerHTML = txt;
	 },
	//设置鼠标移动时位置
	setMouseTipDisplay : function ( v ) {
		this.mouseTip.style.display = v;
	},
	//取得鼠标移动时位置
	getMousePos : function ( point ) {
		var offsetLeft = this.ct.offsetLeft;
		var offsetTop = this.ct.offsetTop + 75;
		if(this.mapType == 'BAIDU'){
			var pos = {x: point.pixel.x, y: point.pixel.y};
		}else{
			var p = point.latLng;
			var latLng = new goome.maps.LatLng(p.lat(), p.lng());
			var pos = overlay.getProjection().fromLatLngToDivPixel(latLng);
		}
		return {left: pos.x + offsetLeft + 10, top: pos.y + offsetTop - 10};
	},
	//拖动范围标记提示
	getTipPos : function ( p ) {
		var offsetLeft = this.ct.offsetLeft;
		var offsetTop = this.ct.offsetTop + 75;
		if(this.mapType == 'BAIDU'){
			var pos = this.map.pointToPixel(p);
		}else{
			var pos = overlay.getProjection().fromLatLngToDivPixel(p);
		}
		return {left: pos.x + offsetLeft + 10, top: pos.y + offsetTop - 10};
	},
	//提交区域报警
	submit : function ( radius , userId , callback ) {		
		var _this = this;
		var r = Math.round(radius);
		var param = "shape_type=1&school_id=" + (parent.custid) + "&user_id=" + userId + "&mds=" + window.mds + 
		"&shape_param=" + this.lat + "," + this.lng + "," + r + "&validate_flag=1&mapType=" + _this.mapType;
		var url = _CONFIG_.UPDATE_URL + "/FenceInfoService?method=saveFenceInfo";

		$.ajax({
			url: url,
			data: param,
			dataType: "jsonp",
			success: function(obj){
				if(obj.success){
					_this.cancel();
					alert(lg.setSuccess + formatKm2M(r/1000));
				}else{
					alert(lg.set + lg.fence + lg.msgtit2);	
				}
				if(callback) callback(obj);
			}
		});		
	}
};